import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import type { API } from '../../src/types/api/response'
import type { Role, RoleQuery, CreateRole, UpdateRole, RoleList, RolePermissionTreeNode } from '../../src/types/api/system/role'

const Random = Mock.Random

// ------------ 常量定义 ------------
const roleStatuses = [
  { value: 0, label: '禁用' },
  { value: 1, label: '正常' }
]

const roleNames = [
  { name: '超级管理员', code: 'SUPER_ADMIN', sort: 1, fixed: true },
  { name: '系统管理员', code: 'SYSTEM_ADMIN', sort: 2, fixed: true },
  { name: '普通用户', code: 'NORMAL_USER', sort: 3, fixed: false },
  { name: '访客', code: 'VISITOR', sort: 4, fixed: false },
  { name: '运营', code: 'OPERATOR', sort: 5, fixed: false },
  { name: '编辑', code: 'EDITOR', sort: 6, fixed: false },
  { name: '测试', code: 'TESTER', sort: 7, fixed: false },
  { name: '开发', code: 'DEVELOPER', sort: 8, fixed: false },
  { name: '财务', code: 'FINANCE', sort: 9, fixed: false },
  { name: '人事', code: 'HR', sort: 10, fixed: false },
  { name: '市场', code: 'MARKETING', sort: 11, fixed: false },
  { name: '销售', code: 'SALES', sort: 12, fixed: false },
  { name: '客服', code: 'CUSTOMER_SERVICE', sort: 13, fixed: false },
  { name: '产品', code: 'PRODUCT', sort: 14, fixed: false },
  { name: '设计', code: 'DESIGNER', sort: 15, fixed: false }
]

// 权限菜单ID列表
const menuIds = [
  'dashboard', 'system', 'system:user', 'system:role', 'system:menu', 'system:dept',
  'system:user:add', 'system:user:edit', 'system:user:delete', 'system:user:export', 'system:user:import',
  'system:role:add', 'system:role:edit', 'system:role:delete', 'system:role:export',
  'system:menu:add', 'system:menu:edit', 'system:menu:delete',
  'system:dept:add', 'system:dept:edit', 'system:dept:delete',
  'config', 'config:dict', 'config:setting', 'config:dict:add', 'config:dict:edit', 'config:dict:delete',
  'config:setting:add', 'config:setting:edit', 'config:setting:delete',
  'monitor', 'monitor:online', 'monitor:job', 'monitor:server', 'monitor:log',
  'tool', 'tool:gen', 'tool:swagger', 'tool:gen:edit', 'tool:gen:remove'
]

// ------------ 工具函数 ------------
/**
 * 生成随机角色数据
 */
const generateRandomRole = (id: string, roleInfo: typeof roleNames[0]): Role => {
  // 固定角色使用固定状态，非固定角色随机状态
  const status = roleInfo.fixed 
    ? 1 
    : roleStatuses[Math.floor(Math.random() * roleStatuses.length)].value
  
  // 为不同角色分配不同数量和类型的权限
  let roleMenuIds: string[] = []
  
  if (roleInfo.name === '超级管理员') {
    // 超级管理员拥有所有权限
    roleMenuIds = [...menuIds]
  } else if (roleInfo.name === '系统管理员') {
    // 系统管理员拥有大部分系统权限
    roleMenuIds = menuIds.filter(id => id.startsWith('system') || id === 'dashboard')
  } else {
    // 其他角色随机分配权限
    const menuCount = Random.natural(3, Math.min(15, menuIds.length))
    const shuffled = [...menuIds].sort(() => 0.5 - Math.random())
    roleMenuIds = shuffled.slice(0, menuCount)
  }
  
  // 创建时间和更新时间
  const createTime = roleInfo.fixed 
    ? '2023-01-01 00:00:00' 
    : Random.datetime('yyyy-MM-dd HH:mm:ss')
  
  const updateTime = Random.datetime('yyyy-MM-dd HH:mm:ss')
  
  // 生成备注
  const remark = roleInfo.fixed 
    ? `系统${roleInfo.name}，拥有${roleInfo.name === '超级管理员' ? '所有' : '系统管理'}权限` 
    : Random.csentence(5, 15)
  
  return {
    id,
    roleName: roleInfo.name,
    roleCode: roleInfo.code,
    roleSort: roleInfo.sort,
    status,
    remark,
    createTime,
    updateTime,
    menuIds: roleMenuIds,
    success: true,
    message: ''
  }
}

/**
 * 生成权限树节点
 */
const generatePermissionTree = (): RolePermissionTreeNode[] => {
  // 创建一个映射来存储所有节点
  const nodeMap = new Map<string, RolePermissionTreeNode>()
  const rootNodes: RolePermissionTreeNode[] = []
  
  // 处理每个菜单ID
  menuIds.forEach(id => {
    const parts = id.split(':')
    let currentId = ''
    let parentId = null
    
    // 为每个层级创建节点
    for (let i = 0; i < parts.length; i++) {
      const part = parts[i]
      const prevId = currentId
      
      // 构建当前层级的ID
      currentId = currentId ? `${currentId}:${part}` : part
      
      // 如果节点已存在，更新parentId
      if (!nodeMap.has(currentId)) {
        // 创建新节点
        const node: RolePermissionTreeNode = {
          id: currentId,
          name: getMenuName(part),
          children: []
        }
        
        nodeMap.set(currentId, node)
        
        // 添加到父节点或根节点列表
        if (i > 0) {
          const parentNode = nodeMap.get(prevId)
          if (parentNode) {
            if (!parentNode.children) {
              parentNode.children = []
            }
            parentNode.children.push(node)
          }
        } else {
          rootNodes.push(node)
        }
      }
    }
  })
  
  return rootNodes
}

/**
 * 根据菜单代码获取菜单名称
 */
const getMenuName = (code: string): string => {
  const menuNames: Record<string, string> = {
    dashboard: '仪表盘',
    system: '系统管理',
    user: '用户管理',
    role: '角色管理',
    menu: '菜单管理',
    dept: '部门管理',
    add: '新增',
    edit: '编辑',
    delete: '删除',
    export: '导出',
    import: '导入',
    config: '参数配置',
    dict: '字典管理',
    setting: '系统设置',
    monitor: '系统监控',
    online: '在线用户',
    job: '定时任务',
    server: '服务监控',
    log: '操作日志',
    tool: '系统工具',
    gen: '代码生成',
    swagger: '系统接口',
    remove: '删除'
  }
  
  return menuNames[code] || code
}

// ------------ 模拟数据 ------------
// 生成角色数据
const roles: Role[] = roleNames.map((roleInfo, index) => 
  generateRandomRole(String(index + 1), roleInfo)
)

// ------------ API 实现 ------------
/**
 * 获取角色列表
 */
const getRoleListApi: MockMethod = {
  url: '/api/system/role/list',
  method: 'get',
  response: ({ query }: { query: RoleQuery }): API.Response<RoleList> => {
    const { keyword, status, page = 1, pageSize = 10 } = query
    let filteredRoles = [...roles]

    // 关键字过滤
    if (keyword) {
      const lowerKeyword = keyword.toLowerCase()
      filteredRoles = filteredRoles.filter(role => 
        role.roleName.toLowerCase().includes(lowerKeyword) || 
        role.roleCode.toLowerCase().includes(lowerKeyword) ||
        (role.remark ? role.remark.toLowerCase().includes(lowerKeyword) : false)
      )
    }

    // 状态过滤
    if (status !== undefined) {
      filteredRoles = filteredRoles.filter(role => role.status === Number(status))
    }

    // 按角色排序字段排序
    filteredRoles.sort((a, b) => a.roleSort - b.roleSort)

    // 修改分页处理代码，在查询中添加数字类型转换
    const pageNum = Number(page)
    const pageSizeNum = Number(pageSize)
    const startIndex = (pageNum - 1) * pageSizeNum
    const endIndex = startIndex + pageSizeNum
    const paginatedRoles = filteredRoles.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list: paginatedRoles,
        total: filteredRoles.length
      }
    }
  }
}

/**
 * 获取角色详情
 */
const getRoleDetailApi: MockMethod = {
  url: '/api/system/role/:id',
  method: 'get',
  response: (options: { url: string }): API.Response<Role | null> => {
    // 从URL中提取ID
    const urlParts = options.url.split('/')
    const id = urlParts[urlParts.length - 1]?.split('?')[0]
    
    if (!id) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误',
        data: null
      }
    }
    
    const role = roles.find(item => item.id === id)
    
    if (!role) {
      return {
        code: 404,
        success: false,
        message: '角色不存在',
        data: null
      }
    }
    
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: role
    }
  }
}

/**
 * 创建角色
 */
const createRoleApi: MockMethod = {
  url: '/api/system/role',
  method: 'post',
  response: ({ body }: { body: CreateRole }): API.Response<Role> => {
    // 检查角色代码是否已存在
    const existingRole = roles.find(role => role.roleCode === body.roleCode)
    if (existingRole) {
      return {
        code: 400,
        success: false,
        message: '角色代码已存在',
        data: null as unknown as Role
      }
    }
    
    const newId = String(Math.max(...roles.map(r => parseInt(r.id))) + 1)
    const now = new Date().toISOString().replace('T', ' ').substring(0, 19)
    
    const newRole: Role = {
      ...body,
      id: newId,
      createTime: now,
      updateTime: now,
      menuIds: body.menuIds || [],
      remark: body.remark || '无',
      success: true,
      message: ''
    }

    roles.push(newRole)
    
    return {
      code: 200,
      success: true,
      message: '创建成功',
      data: newRole
    }
  }
}

/**
 * 更新角色
 */
const updateRoleApi: MockMethod = {
  url: '/api/system/role/:id',
  method: 'put',
  response: (options: { url: string; body: UpdateRole }): API.Response<null> => {
    // 从URL中提取ID
    const urlParts = options.url.split('/')
    const id = urlParts[urlParts.length - 1]?.split('?')[0]
    
    if (!id) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误',
        data: null
      }
    }
    
    const index = roles.findIndex(item => item.id === id)
    if (index === -1) {
      return {
        code: 404,
        success: false,
        message: '角色不存在',
        data: null
      }
    }
    
    // 检查角色代码是否已被其他角色使用
    if (options.body.roleCode) {
      const existingRole = roles.find(role => 
        role.roleCode === options.body.roleCode && role.id !== id
      )
      
      if (existingRole) {
        return {
          code: 400,
          success: false,
          message: '角色代码已存在',
          data: null
        }
      }
    }
    
    // 检查是否是固定角色
    const roleInfo = roleNames.find(r => r.name === roles[index].roleName)
    if (roleInfo?.fixed) {
      // 固定角色只允许修改排序和备注
      roles[index] = {
        ...roles[index],
        roleSort: options.body.roleSort || roles[index].roleSort,
        remark: options.body.remark !== undefined ? options.body.remark : roles[index].remark,
        updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
      }
    } else {
      // 非固定角色可以修改所有字段
      roles[index] = {
        ...roles[index],
        ...options.body,
        updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
      }
    }
    
    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: null
    }
  }
}

/**
 * 删除角色
 */
const deleteRoleApi: MockMethod = {
  url: '/api/system/role',
  method: 'delete',
  response: ({ body }: { body: { ids: string[] } }): API.Response<null> => {
    const { ids } = body
    
    // 检查是否包含固定角色
    const fixedRoles = roles.filter(role => 
      ids.includes(role.id) && 
      roleNames.find(r => r.name === role.roleName && r.fixed)
    )
    
    if (fixedRoles.length > 0) {
      return {
        code: 400,
        success: false,
        message: `无法删除固定角色: ${fixedRoles.map(r => r.roleName).join(', ')}`,
        data: null
      }
    }
    
    const roleIds = new Set(ids)
    const initialLength = roles.length
    roles.splice(0, roles.length, ...roles.filter(role => !roleIds.has(role.id)))
    
    // 检查是否有角色被删除
    if (roles.length === initialLength) {
      return {
        code: 404,
        success: false,
        message: '未找到指定角色',
        data: null
      }
    }
    
    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

/**
 * 修改角色状态
 */
const changeRoleStatusApi: MockMethod = {
  url: '/api/system/role/status/:id',
  method: 'put',
  response: (options: { url: string; body: { status: number } }): API.Response<null> => {
    // 从URL中提取ID
    const urlParts = options.url.split('/')
    const id = urlParts[urlParts.length - 1]?.split('?')[0]
    
    if (!id) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误',
        data: null
      }
    }
    
    const role = roles.find(item => item.id === id)
    
    // 检查角色是否存在
    if (!role) {
      return {
        code: 404,
        success: false,
        message: '角色不存在',
        data: null
      }
    }
    
    // 检查是否是固定角色且状态为禁用
    const roleInfo = roleNames.find(r => r.name === role.roleName)
    if (roleInfo?.fixed && options.body.status === 0) {
      return {
        code: 400,
        success: false,
        message: '无法禁用固定角色',
        data: null
      }
    }
    
    // 更新状态
    role.status = options.body.status
    role.updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19)
    
    return {
      code: 200,
      success: true,
      message: '状态修改成功',
      data: null
    }
  }
}

/**
 * 获取角色权限
 */
const getRolePermissionsApi: MockMethod = {
  url: '/api/system/role/permissions/:id',
  method: 'get',
  response: (options: { url: string }): API.Response<{
    permissionTree: RolePermissionTreeNode[]
    checkedKeys: string[]
  }> => {
    // 从URL中提取ID
    const urlParts = options.url.split('/')
    const id = urlParts[urlParts.length - 1]?.split('?')[0]
    
    if (!id) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误',
        data: {
          permissionTree: [],
          checkedKeys: []
        }
      }
    }
    
    const role = roles.find(item => item.id === id)
    
    // 检查角色是否存在
    if (!role) {
      return {
        code: 404,
        success: false,
        message: '角色不存在',
        data: {
          permissionTree: [],
          checkedKeys: []
        }
      }
    }
    
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        permissionTree: generatePermissionTree(),
        checkedKeys: role.menuIds
      }
    }
  }
}

/**
 * 更新角色权限
 */
const updateRolePermissionsApi: MockMethod = {
  url: '/api/system/role/permissions/:id',
  method: 'put',
  response: (options: { url: string; body: { permissions: string[] } }): API.Response<null> => {
    // 从URL中提取ID
    const urlParts = options.url.split('/')
    const id = urlParts[urlParts.length - 1]?.split('?')[0]
    
    if (!id) {
      return {
        code: 400,
        success: false,
        message: '请求参数错误',
        data: null
      }
    }
    
    const role = roles.find(item => item.id === id)
    
    // 检查角色是否存在
    if (!role) {
      return {
        code: 404,
        success: false,
        message: '角色不存在',
        data: null
      }
    }
    
    // 更新权限
    role.menuIds = options.body.permissions
    role.updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19)
    
    return {
      code: 200,
      success: true,
      message: '权限更新成功',
      data: null
    }
  }
}

// ------------ 导出 ------------
export default [
  getRoleListApi,
  getRoleDetailApi,
  createRoleApi,
  updateRoleApi,
  deleteRoleApi,
  changeRoleStatusApi,
  getRolePermissionsApi,
  updateRolePermissionsApi
] as MockMethod[] 